package com.right.health.app.base;

import android.content.Context;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Base Presenter
 * Created by Hope on 17/3/1.
 */
public abstract class IBasePresenter<T extends IBaseView> {

    private T mView;
    private Object mViewProxy;

    private Context context;

    public IBasePresenter() {}

    /**
     * 注入View，使之能够与View相互响应
     *
     */
    public void attachView(T iView) {
        this.mView = iView;
        mViewProxy = createProxy();
        if(context == null) {
            context = this.mView.getViewContext();
        }
    }

    private Object createProxy() {
        return Proxy.newProxyInstance(mView.getClass().getClassLoader(), mView.getClass().getInterfaces(), new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(mView == null) {
                    return null;
                }

                return method.invoke(mView, args); //代理对象调用真实目标对象的sing方法去处理用户请求
            }
        });
    }

    /**
     * 释放资源
     */
    public void detachView() {
        if(this.mView != null) {
            this.mView = null;
        }
        context = null;
//        mViewProxy = null;
    }

    public void onResume() {

    }

    public void onPause() {

    }

    protected Context getContext() {
        return context;
    }

    protected T getIView() {

        return (T)mViewProxy;
    }


}
